package com.amorcloud.pig.activity;

import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amorcloud.pig.R;
import com.amorcloud.pig.adapter.UploadCheckDataAdapter;
import com.amorcloud.pig.adapter.PigInfoAdapter;
import com.amorcloud.pig.bean.CheckBean;
import com.amorcloud.pig.bean.PigInfoBean;
import com.amorcloud.pig.utils.CheckDaoUtil;
import com.amorcloud.pig.utils.HttpUtils;
import com.amorcloud.pig.utils.NetworkUtil;
import com.amorcloud.pig.utils.PigDaoUtils;
import com.amorcloud.pig.widget.UploadSuccessDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class UploadDetailActivity extends BaseActivity implements View.OnClickListener {

    ListView uploadDataList;
    String uploadType;
    //猪只数据
    List<PigInfoBean> pigList;
    List<PigInfoBean> uploadSuccessPigList;
    List<PigInfoBean> uploadFailPigList;
    PigInfoAdapter pigAdapter;

    //盘点数据
    List<CheckBean> checkBeanList;
    List<CheckBean> uploadSuccessCheckList;
    List<CheckBean> uploadFailCheckList;
    UploadCheckDataAdapter checkDataAdapter;

    //销售数据

    Button startUpload, reUpload;
    int uploadSuccess, uploadFail;
    View header;
    TextView headerTitle1;

    @Override
    protected void init() {
        setContentView(R.layout.activity_upload_detail);
        initCustomToolbar(this);
        initView();
        initData();
    }

    private void initView() {
        uploadDataList = findViewById(R.id.lv_upload_data);
        header = LayoutInflater.from(this).inflate(R.layout.header_upload_data, null);
        headerTitle1 = header.findViewById(R.id.header_title1);
        //uploadDataList.addHeaderView(header);
        startUpload = findViewById(R.id.btn_start_upload);
        startUpload.setOnClickListener(this);
        reUpload = findViewById(R.id.btn_reupload);
        reUpload.setOnClickListener(this);
        reUpload.setEnabled(false);
    }

    private void initData() {
        uploadType = getIntent().getStringExtra("type");

        switch (uploadType) {
            case "base":
                initPigData();
                break;
            case "check":
                initCheckData();
                break;
            case "weaned":
                break;
            case "sell":
                initSellData();
                break;
            default:
                break;
        }
    }

    private void initPigData() {
        deleteUploadSuccessPigData();
        pigList = PigDaoUtils.queryAll();
        pigAdapter = new PigInfoAdapter(this, pigList);
        headerTitle1.setText("仔猪电子耳号");
        uploadDataList.addHeaderView(header);
        uploadDataList.setAdapter(pigAdapter);
    }

    private void deleteUploadSuccessPigData() {
        uploadSuccessPigList = PigDaoUtils.queryWhere("where IS_UPLOAD=?", "1");
        for (int i = 0; i < uploadSuccessPigList.size(); i++) {
            PigDaoUtils.delete(uploadSuccessPigList.get(i));
        }
    }

    private void initCheckData() {
        deleteUploadSuccessCheckData();
        //获取所有数据
        checkBeanList = CheckDaoUtil.queryAllCheckData();
        checkDataAdapter = new UploadCheckDataAdapter(this, checkBeanList);
        headerTitle1.setText("批次号");
        uploadDataList.addHeaderView(header);
        uploadDataList.setAdapter(checkDataAdapter);
    }

    private void deleteUploadSuccessCheckData() {
        //删除已经上传成功的数据
        uploadSuccessCheckList = CheckDaoUtil.queryUploadSuccessCheckData();
        for (CheckBean bean : uploadSuccessCheckList) {
            CheckDaoUtil.delete(bean);
        }
    }

    private void initSellData() {
        deleteUploadSuccessSellData();
        //获取所有数据
        checkBeanList = CheckDaoUtil.queryAllSellData();
        checkDataAdapter = new UploadCheckDataAdapter(this, checkBeanList);
        headerTitle1.setText("销售单号");
        uploadDataList.addHeaderView(header);
        uploadDataList.setAdapter(checkDataAdapter);
    }

    private void deleteUploadSuccessSellData() {
        //删除已经上传成功的数据
        uploadSuccessCheckList = CheckDaoUtil.queryUploadSuccessSellData();
        for (CheckBean bean : uploadSuccessCheckList) {
            CheckDaoUtil.delete(bean);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start_upload:
                if (NetworkUtil.isNetworkConnected(this)) {
                    //showDialog();
                    startUpload(0);
                    startUpload.setEnabled(false);
                } else {
                    Toast.makeText(this, "网络错误，请设置网络。", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_reupload:
                if (NetworkUtil.isNetworkConnected(this)) {
                    uploadSuccess = 0;
                    uploadFail = 0;
                    startUpload(1);
                    reUpload.setEnabled(false);
                } else {
                    Toast.makeText(this, "网络错误，请设置网络。", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * @param uploadTag 0 upload, 1 reupload
     */
    private void startUpload(int uploadTag) {
        switch (uploadType) {
            case "base":
                if (uploadTag == 0) {
                    if (pigList.size() > 0) {
                        baseDataUpload(pigList);
                    }
                } else {
                    uploadFailPigList = PigDaoUtils.queryWhere("where IS_UPLOAD=?", "0");
                    baseDataUpload(uploadFailPigList);
                }
                break;
            case "check":
                if (uploadTag == 0) {
                    if (checkBeanList.size() > 0) {
                        checkDataUpload(checkBeanList);
                    }
                } else {
                    uploadFailCheckList = CheckDaoUtil.queryUploadFailCheckData();
                    checkDataUpload(uploadFailCheckList);
                }
                break;
            case "weaned":
                break;
            case "sell":
                if (uploadTag == 0) {
                    if (checkBeanList.size() > 0) {
                        checkDataUpload(checkBeanList);
                    }
                } else {
                    uploadFailCheckList = CheckDaoUtil.queryUploadFailSellData();
                    checkDataUpload(uploadFailCheckList);
                }
                break;
            default:
                break;
        }
    }

    private void baseDataUpload(final List<PigInfoBean> pigInfoBeans) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < pigInfoBeans.size(); i++) {
                    String result = HttpUtils.uploadBasePigData(pigInfoBeans.get(i));
                    Log.d("leihuiming", "result = " + result);
                    try {
                        JSONObject object = new JSONObject(result);
                        if (object.has("MsgCode")) {
                            if ("0".equals(object.get("MsgCode"))) {
                                PigInfoBean bean = pigInfoBeans.get(i);
                                bean.setIsUpload("1");
                                PigDaoUtils.update(bean);
                                uploadSuccess++;
                            } else {
                                PigInfoBean bean = pigInfoBeans.get(i);
                                bean.setIsUpload("0");
                                PigDaoUtils.update(bean);
                                uploadFail++;
                            }
                        }
                        if (i == pigInfoBeans.size() - 1) {
                            pigList = PigDaoUtils.queryAll();
                            mHandler.sendEmptyMessage(1);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    private void checkDataUpload(final List<CheckBean> beans) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                for (CheckBean bean : beans) {
                    String result = "";
                    if (uploadType.equals("check")) {
                        result = HttpUtils.uploadCheckData(bean.getCheckID(), bean.getCheckErMsg());
                    } else {
                        result = HttpUtils.uploadSellData(bean.getCheckID(), bean.getCheckErMsg());
                    }
                    Log.d("leihuiming", "checkDataUpload result = " + result);
                    try {
                        JSONObject object = new JSONObject(result);
                        if (object.has("MsgCode")) {
                            if ("0".equals(object.get("MsgCode"))) {
                                bean.setUpLoadSuccess("1");
                                CheckDaoUtil.update(bean);
                                uploadSuccess++;
                            } else {
                                bean.setUpLoadSuccess("0");
                                CheckDaoUtil.update(bean);
                                uploadFail++;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                mHandler.sendEmptyMessage(1);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://上传完数据 刷新UI
                    updateListData();
                    //startUpload.setEnabled(true);
                    if (uploadFail > 0) {
                        reUpload.setEnabled(true);
                        startUpload.setEnabled(false);
                    } else {
                        Dialog dialog = UploadSuccessDialog.CreateUploadSuccessDialog(UploadDetailActivity.this, uploadSuccess);
                        dialog.show();
                        final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
                        params.width = 600;
                        params.height = 500;
                        dialog.getWindow().setAttributes(params);
                        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                    }
                    break;
            }
        }
    };

    private void updateListData() {
        switch (uploadType) {
            case "base":
                pigAdapter.setData(pigList);
                break;
            case "check":
                checkBeanList = CheckDaoUtil.queryAllCheckData();
                checkDataAdapter.setData(checkBeanList);
                break;
            case "weaned":
                break;
            case "sell":
                checkBeanList = CheckDaoUtil.queryAllSellData();
                checkDataAdapter.setData(checkBeanList);
                break;
            default:
                break;
        }
    }

    private void showDialog() {
        String count = Html.fromHtml("总数<font color='#FF0000'>" + uploadSuccess + "</font> 条！").toString();
        Log.d("leihuiming", "count = " + count);
        Dialog dialog = UploadSuccessDialog.CreateUploadSuccessDialog(UploadDetailActivity.this, uploadSuccess);
        dialog.show();
        final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = 600;
        params.height = 500;
        dialog.getWindow().setAttributes(params);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
    }
}
